package com.itheima.mall.api.sms;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mall.mapper.sms.HomeAdvertiseMapper;
import com.itheima.mall.pojo.sms.SmsHomeAdvertise;
import com.itheima.mall.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

@DubboService
public class HomeAdvertiseServiceApiImpl implements HomeAdvertiseServiceApi {
    @Autowired
    HomeAdvertiseMapper advertiseMapper;
    @Override
    public void createAdvertise(SmsHomeAdvertise smsHomeAdvertise) {
        advertiseMapper.insert(smsHomeAdvertise);
    }

    @Override
    public void deleteAdvtertise(int[] ids) {
        for (int id : ids) {
            advertiseMapper.deleteById(Convert.toLong(id));
        }
    }

    @Override
    public PageResult<SmsHomeAdvertise> getList(String endTime, String name, Integer pageNum, Integer pageSize, Integer type) {

        try{
            Page<SmsHomeAdvertise> pageInfo=new Page<>(pageNum,pageSize);
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);
            LambdaQueryWrapper<SmsHomeAdvertise> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(date!=null,SmsHomeAdvertise::getEndTime,date);
            queryWrapper.eq(name!=null,SmsHomeAdvertise::getName,name);
            queryWrapper.eq(type!=null,SmsHomeAdvertise::getType,type);
            advertiseMapper.selectPage(pageInfo, queryWrapper);
            PageResult pageResult=new PageResult();
            pageResult.setList(pageInfo.getRecords());
            pageResult.setPageNum(pageNum);
            pageResult.setPageSize(pageSize);
            pageResult.setTotalPage(Convert.toInt(pageInfo.getCurrent()));
            pageResult.setTotal(Convert.toInt(pageInfo.getTotal()));
            return pageResult;
        }catch (Exception e){
        return null;
        }
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        SmsHomeAdvertise advertise=new SmsHomeAdvertise();
        advertise.setStatus(status);
        advertise.setId(Convert.toLong(id));
        advertiseMapper.updateById(advertise);
    }

    @Override
    public void updateAdvertise(SmsHomeAdvertise smsHomeAdvertise) {
        advertiseMapper.updateById(smsHomeAdvertise);
    }

    @Override
    public SmsHomeAdvertise getAdvertise(Integer id) {
        SmsHomeAdvertise advertise = advertiseMapper.selectById(Convert.toLong(id));
        return advertise;
    }
}
